package com.oros.db;

import java.io.Serializable;
import java.util.HashSet;

public class AEForeignKeyConstraint implements AEValidator, Serializable {

	private static final long serialVersionUID = 1L;
    private AETableContainer foreignContainer;
    private String foreignColumn,tableName;
    private int hashcode;
	public AEForeignKeyConstraint(AETableContainer foreignContainer,String foreignColumn) {
		this.foreignContainer = foreignContainer;
		this.foreignColumn = foreignColumn;
		int foreignColumnIndex = foreignContainer.getColumnIndex(foreignColumn);
		if (foreignColumnIndex<0)
			throw new RuntimeException("Foreign key constraint invalid column name "+foreignColumn+" for container "+foreignContainer);
		hashcode = foreignContainer.hashCode() * 31 + foreignColumn.hashCode();
		tableName = foreignContainer.tableName;
	}

	@Override
	public boolean isValid(AETableContainer parent, AERawItem item) {
		HashSet<?> sets=foreignContainer.getDistinctColumnValuesUnfiltered(foreignColumn);
		Object primKey = item.getPrimaryColumnValue();
		if (sets.contains(primKey)) return false;
		return true;
	}

	@Override
	public int hashCode() {
		return hashcode;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		AEForeignKeyConstraint other = (AEForeignKeyConstraint) obj;
		if (foreignColumn == null) {
			if (other.foreignColumn != null)
				return false;
		} else if (!foreignColumn.equals(other.foreignColumn))
			return false;
		if (foreignContainer == null) {
			if (other.foreignContainer != null)
				return false;
		} else if (!foreignContainer.equals(other.foreignContainer))
			return false;
		return true;
	}
	@Override
	public String toString()
	{
		return tableName;
	}

}
